'use strict';
/**
 * @fileoverview VIP
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoose = require('mongoose');
var moment = require('moment');
var _ = require('lodash');
var constantUtil = require('../util/constantUtil');
var dailyEnergyMgr = require('../mgr/dailyEnergyMgr.js');
var dataApi = require('../libs/dataApi');

/**
 *  每日体力领取
 */
var dailyEnergySchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 领取的体力时间
    receive_time_list: [Number]

});

dailyEnergySchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 加入领取时间
 * @return {[type]} [description]
 */
dailyEnergySchema.methods.addTimeList = function (task_id) {
    if (_.indexOf(this.receive_time_list, task_id) == -1) {
        this.receive_time_list.push(task_id);
        return true;
    } else {
        return false;
    }
};

/**
 * 刷新
 * @return {[type]} [description]
 */
dailyEnergySchema.methods.refresh = function () {
    this.receive_time_list = [];
};

/**
 * 获取修改
 * @return {[type]} [description]
 */
dailyEnergySchema.methods.getLastChange = function () {
    return this.toJSON();
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
dailyEnergySchema.methods.push = function () {
    this.pushModify();
};

dailyEnergySchema.methods.pushModify = function () {
    dailyEnergyMgr.sendDailyEnergyChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send vip message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!dailyEnergySchema.options.toJSON) {
    dailyEnergySchema.options.toJSON = {};
}
/* jshint unused:false */
dailyEnergySchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

mongoose.model('DailyEnergy', dailyEnergySchema);
